﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hotnet.Entity;
using Hotnet.Dal.BaseRepository;
using System.Data.Linq;
using Hotnet.Entity.Enum;
using Component.Utilities;
using Hotnet.Entity.Search;

namespace Hotnet.Dal.NSDalPicture
{
	public class DalPictureGroup : Repository<PictureGroup>
	{

		public PictureGroup[] List(int categoryId, int pageNo, int pageSize, out int totalCount)
		{
			totalCount = (from g in diableCacheGiveTable
						  where g.CategoryID == categoryId && g.IsPublished==1
						  select g).Count();

			var groupList = (from g in diableCacheGiveTable
							 where g.CategoryID
								 == categoryId && g.IsPublished==1
							 orderby g.OrderInCategory
							 select g).Skip(pageNo * pageSize).Take(pageSize).ToArray();

			return groupList;
		}

		public PictureGroup[] List(SearchPictureCondition condition,int pageNo,int pageSize,out int totalCount,int? isPublished)
		{
			string pictureOrderByCondtion = "";
			string pictureNameCondition = "";
			string pictureSourceFromCondition = "";
			string pictureDefineTypeCondition = "";
			string pictureCategoryCondition = "";
			string isPublishedCondition = "";
			if (isPublished != null && isPublished!=(int) EnumPublishState.全部)
				isPublishedCondition = string.Format(" and ispublished={0} ",isPublished.Value);

			int from = pageNo * pageSize + 1;
			int to = (pageNo + 1) * pageSize;
			totalCount = 0;
			if (condition.CategoryID != null)
				pictureCategoryCondition=string.Format(" and categoryId={0}", condition.CategoryID);
			if (condition.DefineType != null && condition.DefineType!=-1)
				pictureDefineTypeCondition=string.Format(" and DefineType={0}", condition.DefineType);
			//if (condition.OrderType != null)
			//    sql.AppendFormat("");
			if (!string.IsNullOrEmpty(condition.PictureName))
				pictureNameCondition=string.Format(" and name like '%{0}%'", condition.PictureName);
			if (condition.SourceFromID != null&&condition.SourceFromID!=-1)
				pictureSourceFromCondition=string.Format(" and sourcefromid={0}", condition.SourceFromID);
			if (condition.OrderType == null || condition.OrderType == (int)EnumOrder.添加时间)
				pictureOrderByCondtion = " AddTime ";
			else
				pictureOrderByCondtion = " ClickCount ";

			string strSql = string.Format(@"select * from (SELECT ROW_NUMBER() OVER (ORDER BY {4} desc)AS Row
										,[GroupID]
										,[CoverImageID]
										,[SourceFromID]
										,[Name]
										,[Description]
										,[CategoryID]
										,[OrderInCategory]
										,[ClickCount]
										,[AddTime]
										,[DefineType]
										,[IsPublished]
										FROM [PictureGroup] where 1=1 {0} {1} {2} {3} {7}) t1 WHERE Row between {5} and {6}", pictureNameCondition, pictureSourceFromCondition, pictureDefineTypeCondition, pictureCategoryCondition, pictureOrderByCondtion,from,to,isPublishedCondition);
			string strCount = string.Format(@"select count(*)
									FROM [PictureGroup] where 1=1 {0} {1} {2} {3} {4} ", pictureNameCondition, pictureSourceFromCondition, pictureDefineTypeCondition, pictureCategoryCondition, isPublishedCondition);

			totalCount = disableCacheDataContext.ExecuteQuery<int>(strCount).FirstOrDefault();
			return disableCacheDataContext.ExecuteQuery<PictureGroup>(strSql).ToArray();
		}


		public PictureGroup[] ListTop(int categoryId, int count)
		{
			var groups = (from g in
							  diableCacheGiveTable
						  where g.CategoryID == categoryId && g.IsPublished==1
						  orderby g.AddTime descending
						  select g).Take(count);
			return groups.ToArray();
		}

		/// <summary>
		/// 列出最热的图片组
		/// </summary>
		/// <param name="count"></param>
		/// <returns></returns>
		public PictureGroup[] ListHotGroups(int count)
		{
			var groups = (from g in diableCacheGiveTable
						  where g.IsPublished==1
						  orderby g.ClickCount
							  descending
						  select g)
						.Take(count);
			return groups.ToArray();
		}

		/// <summary>
		/// 列出分类中最热的图片
		/// </summary>
		/// <param name="categoryId"></param>
		/// <param name="count"></param>
		/// <returns></returns>
		public PictureGroup[] ListHotGroups(int categoryId, int count)
		{
			var groups = (from g in diableCacheGiveTable
						  where g.CategoryID == categoryId && g.IsPublished==1
						  orderby
							  g.ClickCount descending
						  select g).Take(count);
			return groups.ToArray();
		}

		public PictureGroup[] ListDefineTypePictureGroup(int count,EnumDefineType defineType)
		{
			var groups = (from g in diableCacheGiveTable
						  where g.DefineType == (int)defineType && g.IsPublished==1
						  orderby g.AddTime descending
						  select g).Take(count);
			return groups.ToArray();
		}

		public PictureGroup[] ListDefineTypePictureGroup(int categoryId, int count, EnumDefineType defineType)
		{
			var groups = (from g in diableCacheGiveTable
						  where g.DefineType == (int)defineType && g.CategoryID == categoryId && g.IsPublished==1
						  select g).Take(count);
			return groups.ToArray();
		}

		/// <summary>
		/// 根据tagNames列出图片组
		/// </summary>
		/// <param name="tagIdList"></param>
		/// <param name="count"></param>
		/// <returns></returns>
		public PictureGroup[] ListReferenceGroupsByTags(IList<string> tagNameList, int count)
		{
			if (tagNameList == null || tagNameList.Count <= 0)
				return new PictureGroup[] { };

			var query = (from g in disableCacheDataContext.PictureGroup
						 join pgxt in disableCacheDataContext.PictureGroupXTag on g.GroupID equals pgxt.GroupID
						 join tag in disableCacheDataContext.Tag on pgxt.TagID equals tag.TagID
						 where tagNameList.ToArray().Contains(tag.TagName) && tag.TargetType == (int)EnumTagType.图片 && g.IsPublished==1
						 select g).Distinct().Take(count);
			var groups = query.ToArray();
			
			return groups;
		}

		/// <summary>
		/// 根据tagNames列出图片组,分页显示
		/// </summary>
		/// <param name="pageSize"></param>
		/// <param name="pageNo"></param>
		/// <param name="totalCount"></param>
		/// <param name="tagNameList"></param>
		/// <returns></returns>
		public PictureGroup[] ListReferenceGroupsByTags(int pageSize,int pageNo,out int totalCount,IList<string> tagNameList)
		{
			totalCount = 0;
			if (tagNameList == null || tagNameList.Count <= 0)
				return new PictureGroup[] { };

			totalCount = (from g in disableCacheDataContext.PictureGroup
						  join pgxt in disableCacheDataContext.PictureGroupXTag on g.GroupID equals pgxt.GroupID
						  join tag in disableCacheDataContext.Tag on pgxt.TagID equals tag.TagID
						  where tagNameList.ToArray().Contains(tag.TagName) && tag.TargetType == (int)EnumTagType.图片 && g.IsPublished==1
						  select g.GroupID).Distinct().Count();

			var query = (from g in disableCacheDataContext.PictureGroup
						 join pgxt in disableCacheDataContext.PictureGroupXTag on g.GroupID equals pgxt.GroupID
						 join tag in disableCacheDataContext.Tag on pgxt.TagID equals tag.TagID
						 where tagNameList.ToArray().Contains(tag.TagName) && tag.TargetType == (int)EnumTagType.图片 && g.IsPublished==1
						 select g).Distinct().Skip(pageNo * pageSize).Take(pageSize);
			var groups = query.ToArray();

			return groups;
		}




		public PictureGroup[] PictureGroupSupplyWhenNotEnough(PictureGroup[] groups, int number)
		{
			if (groups.Count() - number < 0)
			{
				PictureGroup[] extraGroup = (from g in disableCacheDataContext.PictureGroup where !groups.Select(x => x.GroupID).Contains(g.GroupID) && g.IsPublished==1 select g).OrderBy(x => disableCacheDataContext.GetNewId()).Take(number-groups.Count()).ToArray();
				groups = groups.Union(extraGroup).ToArray();
			}
			return groups;
		}

		public PictureGroup[] ListReferenceGroupsByTags(IList<string> tagIdList, int groupId, int count)
		{
			if (tagIdList == null || tagIdList.Count <= 0)
				return new PictureGroup[] { };

			var query = (from g in disableCacheDataContext.PictureGroup
						 join pgxt in disableCacheDataContext.PictureGroupXTag on g.GroupID equals pgxt.GroupID
						 join tag in disableCacheDataContext.Tag on pgxt.TagID equals tag.TagID
						 where tagIdList.ToArray().Contains(tag.TagName) && g.GroupID != groupId && tag.TargetType == (int)EnumTagType.图片 && g.IsPublished==1
						 select g).Distinct().Take(count);
			var groups = query.ToArray();

			return groups;
		}

		public ViewPictureGroup[] ListTopXPictureGroupByCategory(int topNumber)
		{
			string strSql = string.Format(@"select t2.* from PictureCategory t1
										cross apply
										(
											select top {0} PictureGroup.*,Picture.ThumbnailPath as 'CoverImagePath' from PictureGroup,Picture where PictureGroup.CoverImageID=Picture.PictureID and PictureGroup.categoryID=t1.categoryID and PictureGroup.IsPublished=1 order by AddTime desc
										) t2", topNumber);
			return disableCacheDataContext.ExecuteQuery<ViewPictureGroup>(strSql).ToArray();
		}

		/// <summary>
		/// 列出最近几天的 最新图片 
		/// </summary>
		/// <param name="dayBefore"></param>
		/// <param name="count"></param>
		/// <returns></returns>
		public PictureGroup[] ListNewestPictureGroup(int dayBefore, int count)
		{
			var groups = (from g in diableCacheGiveTable
						  where g.IsPublished==1
						  orderby g.AddTime
							  descending
						  select g)
						.Take(count);
			return groups.ToArray();
		}

		public PictureGroup[] ListRecommendPictureGroup(int pageNo, int PAGE_SIZE, out int totalCount, EnumOrder order)
		{
			PictureGroup[] groups = null;
			if (order == EnumOrder.点击次数)
			{
				groups = (from g in diableCacheGiveTable
						  where g.DefineType == (int)EnumDefineType.我的推荐 && g.IsPublished==1
						  select g).OrderByDescending(x => x.ClickCount).Skip(PAGE_SIZE * pageNo).Take(PAGE_SIZE).ToArray();
			}
			else
			{
				groups = (from g in diableCacheGiveTable
						  where g.DefineType == (int)EnumDefineType.我的推荐 && g.IsPublished==1
						  select g).OrderByDescending(x => x.AddTime).Skip(PAGE_SIZE * pageNo).Take(PAGE_SIZE).ToArray();
			}
			totalCount = (from g in diableCacheGiveTable
						  where g.DefineType == (int)EnumDefineType.我的推荐 && g.IsPublished==1
						  select g.GroupID).Count();
			return groups.ToArray();
		}

	}
}
